package de.koller.million.card.frame;

import de.koller.million.card.CNode;
import de.koller.million.card.engine.player.Player;
import de.koller.million.card.frame.player.PlayerFrame;
import java.util.*;
import javax.swing.ComboBoxModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

public class PlayerChooseModel implements ComboBoxModel<Player> {
	
	private final Set<ListDataListener> listener = new HashSet<>();
	private final CNode node;
	private boolean changed = true;
	
	private Player selected = null;
	private List<Player> players = new ArrayList<>();
	
	public PlayerChooseModel( CNode node ) {
		this.node = node;
	}

	@Override
	public Object getSelectedItem() {
		return players.size() + " Spieler";
	}

	@Override
	public void setSelectedItem( Object anItem ) {
		//selected = (Player)anItem;
		PlayerFrame.openPlayerView( (Player)anItem );
	}

	@Override
	public void addListDataListener( ListDataListener l ) {
		listener.add( l );
	}

	@Override
	public Player getElementAt( int index ) {
		if( players == null )
			return null;
		
		return players.get( index );
	}

	@Override
	public int getSize() {
		if( players == null )
			return 0;
		
		return players.size();
	}

	@Override
	public void removeListDataListener( ListDataListener l ) {
		listener.remove( l );
	}

	public void setChanged() {
		this.changed = true;
	}

	public void update() {
		if( !this.changed )
			return;	
		if( node.croot == null )
			return;
		
		players.clear();
		for( Player p : node.croot.engine.playerContainer.players )
			players.add( p );
		Collections.sort( players, new Comparator<Player>() {
			@Override public int compare( Player o1, Player o2 ) {
				return Integer.compare( o1.id, o2.id );
			}
		} );
		
		for( ListDataListener i : listener )
			i.contentsChanged( new ListDataEvent( node, ListDataEvent.CONTENTS_CHANGED, 0, getSize() ) );
		
		this.changed = false;
	}
	
}
